package com.wedimob.pool;

import java.util.HashMap;
import java.util.Map;

import nf.fr.eraasoft.pool.ObjectPool;
import nf.fr.eraasoft.pool.PoolSettings;
import nf.fr.eraasoft.pool.PoolableObjectBase;

import com.google.gson.Gson;

public class PoolManager {

	private static final Map<Class<?>, ObjectPool<?>> cache = new HashMap<Class<?>, ObjectPool<?>>();

	@SuppressWarnings("unchecked")
	public static <T> ObjectPool<T> get(Class<T> cl) {
		if (cache.containsKey(cl))
			return (ObjectPool<T>) cache.get(cl);

		PoolSettings<?> poolSettings = null;
		if (cl == Gson.class) {
			poolSettings = new PoolSettings<Gson>(
					new PoolableObjectBase<Gson>() {
						@Override
						public Gson make() {
							return new Gson();
						}

						@Override
						public void activate(Gson t) {
						}
					});
			// Add some settings
			poolSettings.min(0).max(10);
		} else if (cl == StringBuilder.class) {
			poolSettings = new PoolSettings<StringBuilder>(
					new PoolableObjectBase<StringBuilder>() {
						@Override
						public StringBuilder make() {
							return new StringBuilder(128);
						}

						@Override
						public void activate(StringBuilder t) {
							t.setLength(0);
						}
					});
			// Add some settings
			poolSettings.min(0).max(10);
		}
		if(poolSettings == null)
			throw new RuntimeException("Cannot pool " + cl);
		
		return (ObjectPool<T>) poolSettings.pool();
	}
}
